#include "chat.h"

void* share_memory = NULL;

int main(){
    key_t key = ftok(".", 20210106);
    int shmid;
    if((shmid = shmget(key, sizeof(struct Msg), IPC_CREAT | 0666)) < 0){
        perror("shmget");
        exit(1);
    }

    if((share_memory = shmat(shmid, NULL, 0)) == (void*)-1){
        perror("shmat");
        exit(1);
    }

    struct Msg* message = (struct Msg*)share_memory;
    memset(message, 0, sizeof(struct Msg));
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutex_init(&message->mutex, &attr);

    pthread_condattr_t c_attr;
    pthread_condattr_init(&c_attr);
    pthread_condattr_setpshared(&c_attr, PTHREAD_PROCESS_SHARED);
    pthread_cond_init(&message->cond, &c_attr);

    //char temp[] = "server";
    //strcpy(message->name, temp);

    while(1){
        pthread_mutex_lock(&message->mutex);
        printf("get lock.\n");
        pthread_cond_wait(&message->cond, &message->mutex);
        printf("<%s> : %s\n", message->name, message->msg);
        memset(message->msg, 0, sizeof(message->msg));
        pthread_mutex_unlock(&message->mutex);
    }
    return 0;
}